package com.yiyi.credit.manage.abutment.manage.common.handler;

import com.yiyi.credit.manage.abutment.common.utils.StringUtil;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import static org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING;


public class ExcelHandel {

    private static XSSFWorkbook workBook = null;
    private static XSSFSheet sheet = null;


    public static void createExcelHeader(LinkedHashMap<String, Object> excelHeader, String sheetName) {

        workBook = new XSSFWorkbook();
        sheet = workBook.createSheet(sheetName);

        Header header = sheet.getHeader();
        header.setCenter(sheetName);
        XSSFRow headerRow = sheet.createRow((short) 0);
        int index = 0;
        for (Map.Entry<String, Object> entry : excelHeader.entrySet()) {

            XSSFCell headerCell = headerRow.createCell(index, CELL_TYPE_STRING);
            index++;
            headerCell.setCellValue(StringUtil.objToStr(entry.getValue()));
        }
    }


    public static void createTableRow(LinkedHashMap<String, Object> excelHeader, Map<String, Object> map, int rowIndex) {

        XSSFRow row = sheet.createRow(rowIndex);
        int mapIndex = 0;
        for (Map.Entry<String, Object> entry : excelHeader.entrySet()) {
            XSSFCell cell = row.createCell(mapIndex);
            cell.setCellValue(StringUtil.objToStr(map.get(entry.getKey())));
            mapIndex++;
        }

    }


    public static void exportExcel(HttpServletResponse response, String fileName) throws IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
        workBook.write(response.getOutputStream());
    }
}
